package com.fly.locks.thread.atomic;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import org.apache.commons.lang3.RandomUtils;
import org.springframework.util.StopWatch;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class AtomicIntegerThread implements Runnable
{
    private AtomicInteger count = new AtomicInteger(0);
    
    @Override
    public void run()
    {
        if (count.get() >= 5)
        {
            log.info("请求用户过多,请稍后再试! 计数器：{}", count.get());
            return;
        }
        try
        {
            log.info("业务处理开始,计数器自增：{}", count.incrementAndGet());
            
            // 模拟耗时业务操作
            log.info("★★★★★★★★ 报名或抢购处理中★★★★★★★★");
            StopWatch clock = new StopWatch();
            clock.start();
            TimeUnit.MILLISECONDS.sleep(RandomUtils.nextInt(10000, 20000));
            clock.stop();
            log.info("运行 {} ms ---------------", clock.getLastTaskTimeMillis());
        }
        catch (InterruptedException e)
        {
            log.error(e.getMessage());
        }
        finally
        {
            log.info("业务处理完毕,计数器自减：{}", count.decrementAndGet());
        }
    }
}
